<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
  <meta name="theme-color" content="#222">
  <meta name="generator" content="Hexo 5.4.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

  <link rel="stylesheet" href="/css/main.css">



  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.2/css/all.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">

  <script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {
      "hostname": "holidaypenguin.gitee.io",
      "root": "/",
      "images": "/images",
      "scheme": "Mist",
      "version": "8.2.2",
      "exturl": false,
      "sidebar": {
        "position": "right",
        "display": "always",
        "padding": 18,
        "offset": 12
      },
      "copycode": true,
      "bookmark": {
        "enable": false,
        "color": "#222",
        "save": "auto"
      },
      "fancybox": false,
      "mediumzoom": false,
      "lazyload": false,
      "pangu": false,
      "comments": {
        "style": "tabs",
        "active": null,
        "storage": true,
        "lazyload": false,
        "nav": null
      },
      "motion": {
        "enable": true,
        "async": true,
        "transition": {
          "post_block": "fadeIn",
          "post_header": "fadeInDown",
          "post_body": "fadeInDown",
          "coll_header": "fadeInLeft",
          "sidebar": "slideUpIn"
        }
      },
      "prism": false,
      "i18n": {
        "placeholder": "搜索...",
        "empty": "没有找到任何搜索结果：${query}",
        "hits_time": "找到 ${hits} 个搜索结果（用时 ${time} 毫秒）",
        "hits": "找到 ${hits} 个搜索结果"
      },
      "path": "/search.xml",
      "localsearch": {
        "enable": true,
        "trigger": "auto",
        "top_n_per_article": 1,
        "unescape": false,
        "preload": false
      }
    };
  </script>
  <meta property="og:type" content="article">
  <meta property="og:title" content="解决canvas图片getImageData,toDataURL跨域问题">
  <meta property="og:url" content="https://holidaypenguin.gitee.io/blob/2019-03-25-solve-the-cross-domain-problem-of-canvas-image-getimagedata-and-todataurl/index.html">
  <meta property="og:site_name" content="HolidayPenguin">
  <meta property="og:locale" content="zh_CN">
  <meta property="og:image" content="https://holidaypenguin.gitee.io/images/js/0001.png">
  <meta property="og:image" content="https://holidaypenguin.gitee.io/images/js/0002.png">
  <meta property="article:published_time" content="2019-03-25T10:31:02.000Z">
  <meta property="article:modified_time" content="2019-03-25T10:31:02.000Z">
  <meta property="article:author" content="holidaypenguin">
  <meta property="article:tag" content="canvas">
  <meta property="article:tag" content="跨域">
  <meta property="article:tag" content="getImageData">
  <meta property="article:tag" content="toDataURL">
  <meta name="twitter:card" content="summary">
  <meta name="twitter:image" content="https://holidaypenguin.gitee.io/images/js/0001.png">


  <link rel="canonical" href="https://holidaypenguin.gitee.io/blob/2019-03-25-solve-the-cross-domain-problem-of-canvas-image-getimagedata-and-todataurl/">


  <script class="page-configurations">
    // https://hexo.io/docs/variables.html
    CONFIG.page = {
      sidebar: "",
      isHome: false,
      isPost: true,
      lang: 'zh-CN'
    };
  </script>
  <title>解决canvas图片getImageData,toDataURL跨域问题 | HolidayPenguin</title>





  <noscript>
    <style>
      body {
        margin-top: 2rem;
      }

      .use-motion .menu-item,
      .use-motion .sidebar,
      .use-motion .post-block,
      .use-motion .pagination,
      .use-motion .comments,
      .use-motion .post-header,
      .use-motion .post-body,
      .use-motion .collection-header {
        visibility: visible;
      }

      .use-motion .header,
      .use-motion .site-brand-container .toggle,
      .use-motion .footer {
        opacity: initial;
      }

      .use-motion .site-title,
      .use-motion .site-subtitle,
      .use-motion .custom-logo-image {
        opacity: initial;
        top: initial;
      }

      .use-motion .logo-line {
        transform: scaleX(1);
      }

      .search-pop-overlay,
      .sidebar-nav {
        display: none;
      }

      .sidebar-panel {
        display: block;
      }
    </style>
  </noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner">
        <div class="site-brand-container">
          <div class="site-nav-toggle">
            <div class="toggle" aria-label="切换导航栏" role="button">
              <span class="toggle-line"></span>
              <span class="toggle-line"></span>
              <span class="toggle-line"></span>
            </div>
          </div>

          <div class="site-meta">

            <a href="/" class="brand" rel="start">
              <i class="logo-line"></i>
              <h1 class="site-title">HolidayPenguin</h1>
              <i class="logo-line"></i>
            </a>
          </div>

          <div class="site-nav-right">
            <div class="toggle popup-trigger">
              <i class="fa fa-search fa-fw fa-lg"></i>
            </div>
          </div>
        </div>



        <nav class="site-nav">
          <ul class="main-menu menu">
            <li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li>
            <li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li>
            <li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li>
            <li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li>
            <li class="menu-item menu-item-search">
              <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
              </a>
            </li>
          </ul>
        </nav>



        <div class="search-pop-overlay">
          <div class="popup search-popup">
            <div class="search-header">
              <span class="search-icon">
                <i class="fa fa-search"></i>
              </span>
              <div class="search-input-container">
                <input autocomplete="off" autocapitalize="off" maxlength="80" placeholder="搜索..." spellcheck="false" type="search" class="search-input">
              </div>
              <span class="popup-btn-close" role="button">
                <i class="fa fa-times-circle"></i>
              </span>
            </div>
            <div class="search-result-container no-result">
              <div class="search-result-icon">
                <i class="fa fa-spinner fa-pulse fa-5x"></i>
              </div>
            </div>

          </div>
        </div>

      </div>


      <div class="toggle sidebar-toggle" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
      </div>

      <aside class="sidebar">

        <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
          <ul class="sidebar-nav">
            <li class="sidebar-nav-toc">
              文章目录
            </li>
            <li class="sidebar-nav-overview">
              站点概览
            </li>
          </ul>

          <div class="sidebar-panel-container">
            <!--noindex-->
            <div class="post-toc-wrap sidebar-panel">
              <div class="post-toc animated">
                <ol class="nav">
                  <li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%9B%BE%E7%89%87%E6%9C%8D%E5%8A%A1%E5%99%A8%E9%9C%80%E8%A6%81%E9%85%8D%E7%BD%AEAccess-Control-Allow-Origin"><span class="nav-number">1.</span> <span class="nav-text">图片服务器需要配置Access-Control-Allow-Origin</span></a></li>
                  <li class="nav-item nav-level-1"><a class="nav-link" href="#canvas%E5%9B%BE%E7%89%87getImageData-cross-origin%E8%B7%A8%E5%9F%9F%E9%97%AE%E9%A2%98"><span class="nav-number">2.</span> <span class="nav-text">canvas图片getImageData cross-origin跨域问题</span></a></li>
                  <li class="nav-item nav-level-1"><a class="nav-link" href="#HTML-crossOrigin%E5%B1%9E%E6%80%A7%E8%A7%A3%E5%86%B3%E8%B5%84%E6%BA%90%E8%B7%A8%E5%9F%9F%E9%97%AE%E9%A2%98"><span class="nav-number">3.</span> <span class="nav-text">HTML crossOrigin属性解决资源跨域问题</span></a>
                    <ol class="nav-child">
                      <li class="nav-item nav-level-2"><a class="nav-link" href="#crossOrigin%E5%85%BC%E5%AE%B9%E6%80%A7"><span class="nav-number">3.1.</span> <span class="nav-text">crossOrigin兼容性</span></a></li>
                    </ol>
                  </li>
                  <li class="nav-item nav-level-1"><a class="nav-link" href="#crossOrigin%E5%B1%9E%E6%80%A7%E4%B8%BA%E4%BB%80%E4%B9%88%E5%8F%AF%E4%BB%A5%E8%A7%A3%E5%86%B3%E8%B5%84%E6%BA%90%E8%B7%A8%E5%9F%9F%E9%97%AE%E9%A2%98%EF%BC%9F"><span class="nav-number">4.</span> <span class="nav-text">crossOrigin属性为什么可以解决资源跨域问题？</span></a></li>
                  <li class="nav-item nav-level-1"><a class="nav-link" href="#IE10%E6%B5%8F%E8%A7%88%E5%99%A8%E4%B8%8D%E6%94%AF%E6%8C%81crossOrigin%E6%80%8E%E4%B9%88%E5%8A%9E%EF%BC%9F"><span class="nav-number">5.</span> <span class="nav-text">IE10浏览器不支持crossOrigin怎么办？</span></a></li>
                </ol>
              </div>
            </div>
            <!--/noindex-->

            <div class="site-overview-wrap sidebar-panel">
              <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
                <p class="site-author-name" itemprop="name">holidaypenguin</p>
                <div class="site-description" itemprop="description"></div>
              </div>
              <div class="site-state-wrap site-overview-item animated">
                <nav class="site-state">
                  <div class="site-state-item site-state-posts">
                    <a href="/archives/">

                      <span class="site-state-item-count">138</span>
                      <span class="site-state-item-name">日志</span>
                    </a>
                  </div>
                  <div class="site-state-item site-state-categories">
                    <a href="/categories/">

                      <span class="site-state-item-count">26</span>
                      <span class="site-state-item-name">分类</span></a>
                  </div>
                  <div class="site-state-item site-state-tags">
                    <a href="/tags/">

                      <span class="site-state-item-count">234</span>
                      <span class="site-state-item-name">标签</span></a>
                  </div>
                </nav>
              </div>
              <div class="links-of-author site-overview-item animated">
                <span class="links-of-author-item">
                  <a href="https://github.com/holidaypenguin" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;holidaypenguin" rel="noopener" target="_blank"><i class="github fa-fw"></i>GitHub</a>
                </span>
                <span class="links-of-author-item">
                  <a href="mailto:songshipeng2016@gmail.com" title="E-Mail → mailto:songshipeng2016@gmail.com" rel="noopener" target="_blank"><i class="envelope fa-fw"></i>E-Mail</a>
                </span>
              </div>



            </div>
          </div>
        </div>
      </aside>
      <div class="sidebar-dimmer"></div>


    </header>


    <div class="back-to-top" role="button">
      <i class="fa fa-arrow-up"></i>
      <span>0%</span>
    </div>

    <noscript>
      <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
    </noscript>


    <div class="main-inner post posts-expand">





      <div class="post-block">



        <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
          <link itemprop="mainEntityOfPage" href="https://holidaypenguin.gitee.io/blob/2019-03-25-solve-the-cross-domain-problem-of-canvas-image-getimagedata-and-todataurl/">

          <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
            <meta itemprop="image" content="/images/avatar.gif">
            <meta itemprop="name" content="holidaypenguin">
            <meta itemprop="description" content="">
          </span>

          <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
            <meta itemprop="name" content="HolidayPenguin">
          </span>
          <header class="post-header">
            <h1 class="post-title" itemprop="name headline">
              解决canvas图片getImageData,toDataURL跨域问题
            </h1>

            <div class="post-meta-container">
              <div class="post-meta">
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-calendar"></i>
                  </span>
                  <span class="post-meta-item-text">发表于</span>

                  <time title="创建时间：2019-03-25 18:31:02" itemprop="dateCreated datePublished" datetime="2019-03-25T18:31:02+08:00">2019-03-25</time>
                </span>
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-folder"></i>
                  </span>
                  <span class="post-meta-item-text">分类于</span>
                  <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                    <a href="/categories/JavaScript/" itemprop="url" rel="index"><span itemprop="name">JavaScript</span></a>
                  </span>
                </span>


                <span id="/blob/2019-03-25-solve-the-cross-domain-problem-of-canvas-image-getimagedata-and-todataurl/" class="post-meta-item leancloud_visitors" data-flag-title="解决canvas图片getImageData,toDataURL跨域问题" title="阅读次数">
                  <span class="post-meta-item-icon">
                    <i class="far fa-eye"></i>
                  </span>
                  <span class="post-meta-item-text">阅读次数：</span>
                  <span class="leancloud-visitors-count"></span>
                </span>
              </div>

              <div class="post-description">
                <!-- more -->
              </div>
            </div>
          </header>




          <div class="post-body" itemprop="articleBody">
            <blockquote>
              <p>本篇文字出处<a target="_blank" rel="noopener" href="https://www.zhangxinxu.com/wordpress/2018/02/crossorigin-canvas-getimagedata-cors/">https://www.zhangxinxu.com/wordpress/2018/02/crossorigin-canvas-getimagedata-cors/</a></p>
            </blockquote>
            <h1 id="图片服务器需要配置Access-Control-Allow-Origin"><a href="#图片服务器需要配置Access-Control-Allow-Origin" class="headerlink" title="图片服务器需要配置Access-Control-Allow-Origin"></a>图片服务器需要配置Access-Control-Allow-Origin</h1>
            <p>一般团队都会有一个专门域名放置静态资源，例如腾讯是gtimg.com，百度是bdimg.com；或者很多团队使用的是腾讯云或者阿里云的服务。</p>
            <p>而主页面所在域名往往不一样，当需要需要对canvas图片进行<code>getImageData()</code>或<code>toDataURL()</code>操作的时候，跨域问题就出来了，而且跨域问题还不止一层。</p>
            <p>首先，第一步，图片服务器需要配置Access-Control-Allow-Origin信息，例如：</p>
            <p>如PHP添加响应头信息，<code>*</code>通配符表示允许任意域名：</p>
            <figure class="highlight plain">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">header(&quot;Access-Control-Allow-Origin: *&quot;);</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>
            <p>或者指定域名：</p>
            <figure class="highlight plain">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">header(&quot;Access-Control-Allow-Origin: www.zhangxinxu.com&quot;);</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>
            <p>此时，Chrome浏览器就不会有<code>Access-Control-Allow-Origin</code>相关的错误信息了，但是，还会有其他的跨域错误信息。</p>
            <h1 id="canvas图片getImageData-cross-origin跨域问题"><a href="#canvas图片getImageData-cross-origin跨域问题" class="headerlink" title="canvas图片getImageData cross-origin跨域问题"></a>canvas图片getImageData cross-origin跨域问题</h1>
            <p>对于跨域的图片，只要能够在网页中正常显示出来，就可以使用canvas的<code>drawImage()</code> API绘制出来。但是如果你想更进一步，通过<code>getImageData()</code>方法获取图片的完整的像素信息，则多半会出错。</p>
            <p>举例来说，使用下面代码获取github上的自己头像图片信息：</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="keyword">var</span> canvas = <span class="built_in">document</span>.createElement(<span class="string">&#x27;canvas&#x27;</span>);</span><br><span class="line"><span class="keyword">var</span> context = canvas.getContext(<span class="string">&#x27;2d&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> img = <span class="keyword">new</span> Image();</span><br><span class="line">img.onload = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    context.drawImage(<span class="built_in">this</span>, <span class="number">0</span>, <span class="number">0</span>);</span><br><span class="line">    context.getImageData(<span class="number">0</span>, <span class="number">0</span>, <span class="built_in">this</span>.width, <span class="built_in">this</span>.height);</span><br><span class="line">&#125;;</span><br><span class="line">img.src = <span class="string">&#x27;https://avatars3.githubusercontent.com/u/496048?s=120&amp;v=4&#x27;</span>;<span class="string">&#x27;;</span></span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>
            <p>结果在Chrome浏览器下显示如下错误：</p>
            <blockquote>
              <p>Uncaught DOMException: Failed to execute ‘getImageData’ on ‘CanvasRenderingContext2D’: The canvas has been tainted by cross-origin data.</p>
            </blockquote>
            <p>出错信息截图</p>
            <p><img src="" data-original="/images/js/0001.png" alt="0001"></p>
            <p>Firefox浏览器错误为：</p>
            <blockquote>
              <p>SecurityError: The operation is insecure.</p>
            </blockquote>
            <p>如果使用的是canvas.toDataURL()方法，则会报：</p>
            <blockquote>
              <p>Failed to execute ‘toDataURL’ on　’HTMLCanvasElement’: Tainted canvased may not be exported</p>
            </blockquote>
            <p>原因其实都是一样的，跨域导致。</p>
            <p>那有没有什么办法可以解决这个问题呢？</p>
            <p>可以试试<code>crossOrigin</code>属性。</p>
            <h1 id="HTML-crossOrigin属性解决资源跨域问题"><a href="#HTML-crossOrigin属性解决资源跨域问题" class="headerlink" title="HTML crossOrigin属性解决资源跨域问题"></a>HTML crossOrigin属性解决资源跨域问题</h1>
            <p>在HTML5中，有些元素提供了支持CORS(Cross-Origin Resource Sharing)（跨域资源共享）的属性，这些元素包括<code>&lt;img&gt;</code>，<code>&lt;video&gt;</code>，<code>&lt;script&gt;</code>等，而提供的属性名就是<code>crossOrigin</code>属性。</p>
            <p>因此，上面的跨域问题可以这么处理：</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="keyword">var</span> canvas = <span class="built_in">document</span>.createElement(<span class="string">&#x27;canvas&#x27;</span>);</span><br><span class="line"><span class="keyword">var</span> context = canvas.getContext(<span class="string">&#x27;2d&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> img = <span class="keyword">new</span> Image();</span><br><span class="line">img.crossOrigin = <span class="string">&#x27;&#x27;</span>;</span><br><span class="line">img.onload = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    context.drawImage(<span class="built_in">this</span>, <span class="number">0</span>, <span class="number">0</span>);</span><br><span class="line">    context.getImageData(<span class="number">0</span>, <span class="number">0</span>, <span class="built_in">this</span>.width, <span class="built_in">this</span>.height);</span><br><span class="line">&#125;;</span><br><span class="line">img.src = <span class="string">&#x27;https://avatars3.githubusercontent.com/u/496048?s=120&amp;v=4&#x27;</span>;<span class="string">&#x27;;</span></span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>
            <p>增加一个<code>img.crossOrigin = &#39;&#39;</code>即可，虽然JS代码这里设置的是空字符串，实际上起作用的属性值是<code>anonymous</code>。</p>
            <p>crossOrigin可以有下面两个值：</p>
            <table>
              <thead>
                <tr>
                  <th>关键字</th>
                  <th>释义</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td>anonymous</td>
                  <td>元素的跨域资源请求不需要凭证标志设置。</td>
                </tr>
                <tr>
                  <td>use-credentials</td>
                  <td>元素的跨域资源请求需要凭证标志设置，意味着该请求需要提供凭证。</td>
                </tr>
              </tbody>
            </table>
            <p>其中，只要<code>crossOrigin</code>的属性值不是<code>use-credentials</code>，全部都会解析为<code>anonymous</code>，包括空字符串，包括类似<code>&#39;abc&#39;</code>这样的字符。</p>
            <p>例如：</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">img.crossOrigin = <span class="string">&#x27;abc&#x27;</span>;</span><br><span class="line"><span class="built_in">console</span>.log(img.crossOrigin);    <span class="comment">// 结果是&#x27;anonymous&#x27;</span></span><br><span class="line">crossOrigin解析为anonymous</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>另外还有一点需要注意，那就是虽然没有<code>crossOrigin</code>属性，和设置<code>crossOrigin=&quot;use-credentials&quot;</code>在默认情况下都会报跨域出错，但是性质上却不一样，两者有较大区别。</p>
            <h2 id="crossOrigin兼容性"><a href="#crossOrigin兼容性" class="headerlink" title="crossOrigin兼容性"></a>crossOrigin兼容性</h2>
            <p>IE11+(IE Edge)，Safari，Chrome，Firefox浏览器均支持，IE9和IE10会报SecurityError安全错误，如下截图：</p>
            <p><img src="" data-original="/images/js/0002.png" alt="0002"></p>
            <h1 id="crossOrigin属性为什么可以解决资源跨域问题？"><a href="#crossOrigin属性为什么可以解决资源跨域问题？" class="headerlink" title="crossOrigin属性为什么可以解决资源跨域问题？"></a>crossOrigin属性为什么可以解决资源跨域问题？</h1>
            <p><code>crossOrigin=anonymous</code>相对于告诉对方服务器，你不需要带任何非匿名信息过来。例如cookie，因此，当前浏览器肯定是安全的。</p>
            <p>就好比你要去别人家里拿一件衣服，<code>crossOrigin=anonymous</code>相对于告诉对方，我只要衣服，其他都不要。如果不说，可能对方在衣服里放个窃听器什么的，就不安全了，浏览器就会阻止。</p>
            <h1 id="IE10浏览器不支持crossOrigin怎么办？"><a href="#IE10浏览器不支持crossOrigin怎么办？" class="headerlink" title="IE10浏览器不支持crossOrigin怎么办？"></a>IE10浏览器不支持crossOrigin怎么办？</h1>
            <p>我们请求图片的时候，不是直接通过<code>new Image()</code>，而是借助ajax和<code>URL.createObjectURL()</code>方法曲线救国。</p>
            <p>代码如下：</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="keyword">var</span> xhr = <span class="keyword">new</span> XMLHttpRequest();</span><br><span class="line">xhr.onload = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> url = URL.createObjectURL(<span class="built_in">this</span>.response);</span><br><span class="line">    <span class="keyword">var</span> img = <span class="keyword">new</span> Image();</span><br><span class="line">    img.onload = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="comment">// 此时你就可以使用canvas对img为所欲为了</span></span><br><span class="line">        <span class="comment">// ... code ...</span></span><br><span class="line">        <span class="comment">// 图片用完后记得释放内存</span></span><br><span class="line">        URL.revokeObjectURL(url);</span><br><span class="line">    &#125;;</span><br><span class="line">    img.src = url;</span><br><span class="line">&#125;;</span><br><span class="line">xhr.open(<span class="string">&#x27;GET&#x27;</span>, url, <span class="literal">true</span>);</span><br><span class="line">xhr.responseType = <span class="string">&#x27;blob&#x27;</span>;</span><br><span class="line">xhr.send();</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>此方法不仅IE10浏览器OK，原本支持crossOrigin的诸位浏览器也是支持的。</p>
            <p>也就多走一个ajax请求，还可以！</p>
            <p>根据，根据实践发现，在IE浏览器下，如果请求的图片过大，几千像素那种，图片会加载失败，我猜是超过了blob尺寸限制。</p>

          </div>





          <footer class="post-footer">
            <div class="post-tags">
              <a href="/tags/canvas/" rel="tag"># canvas</a>
              <a href="/tags/%E8%B7%A8%E5%9F%9F/" rel="tag"># 跨域</a>
              <a href="/tags/getImageData/" rel="tag"># getImageData</a>
              <a href="/tags/toDataURL/" rel="tag"># toDataURL</a>
            </div>



            <div class="post-nav">
              <div class="post-nav-item">
                <a href="/blob/2019-03-25-free-bitmap-font/" rel="prev" title="免费的位图字体制作工具Bitmap Font">
                  <i class="fa fa-chevron-left"></i> 免费的位图字体制作工具Bitmap Font
                </a>
              </div>
              <div class="post-nav-item">
                <a href="/blob/2019-03-26-realization-of-waterfall-flow-layout/" rel="next" title="瀑布流布局实现">
                  瀑布流布局实现 <i class="fa fa-chevron-right"></i>
                </a>
              </div>
            </div>
          </footer>
        </article>
      </div>







      <script>
        window.addEventListener('tabs:register', () => {
          let {
            activeClass
          } = CONFIG.comments;
          if (CONFIG.comments.storage) {
            activeClass = localStorage.getItem('comments_active') || activeClass;
          }
          if (activeClass) {
            const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
            if (activeTab) {
              activeTab.click();
            }
          }
        });
        if (CONFIG.comments.storage) {
          window.addEventListener('tabs:click', event => {
            if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
            const commentClass = event.target.classList[1];
            localStorage.setItem('comments_active', commentClass);
          });
        }
      </script>
    </div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


      <div class="copyright">
        &copy;
        <span itemprop="copyrightYear">2021</span>
        <span class="with-love">
          <i class="fa fa-heart"></i>
        </span>
        <span class="author" itemprop="copyrightHolder">holidaypenguin</span>
      </div>
      <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/mist/" class="theme-link" rel="noopener" target="_blank">NexT.Mist</a> 强力驱动
      </div>

    </div>
  </footer>


  <script size="300" alpha="0.1" zIndex="-1" src="https://cdn.jsdelivr.net/npm/ribbon.js@1.0.2/dist/ribbon.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
  <script src="/js/love.js"></script>

  <script src="/js/development.js"></script>
  <script src="/js/utils.js"></script>
  <script src="/js/motion.js"></script>
  <script src="/js/schemes/muse.js"></script>
  <script src="/js/next-boot.js"></script>


  <script src="/js/local-search.js"></script>









  <script>
    (function() {
      function leancloudSelector(url) {
        url = encodeURI(url);
        return document.getElementById(url).querySelector('.leancloud-visitors-count');
      }

      function addCount(Counter) {
        const visitors = document.querySelector('.leancloud_visitors');
        const url = decodeURI(visitors.id);
        const title = visitors.dataset.flagTitle;

        Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify({
            url
          })))
          .then(response => response.json())
          .then(({
            results
          }) => {
            if (results.length > 0) {
              const counter = results[0];
              leancloudSelector(url).innerText = counter.time + 1;
              Counter('put', '/classes/Counter/' + counter.objectId, {
                  time: {
                    '__op': 'Increment',
                    'amount': 1
                  }
                })
                .catch(error => {
                  console.error('Failed to save visitor count', error);
                });
            } else {
              Counter('post', '/classes/Counter', {
                  title,
                  url,
                  time: 1
                })
                .then(response => response.json())
                .then(() => {
                  leancloudSelector(url).innerText = 1;
                })
                .catch(error => {
                  console.error('Failed to create', error);
                });
            }
          })
          .catch(error => {
            console.error('LeanCloud Counter Error', error);
          });
      }

      function showTime(Counter) {
        const visitors = document.querySelectorAll('.leancloud_visitors');
        const entries = [...visitors].map(element => {
          return decodeURI(element.id);
        });

        Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify({
            url: {
              '$in': entries
            }
          })))
          .then(response => response.json())
          .then(({
            results
          }) => {
            for (let url of entries) {
              const target = results.find(item => item.url === url);
              leancloudSelector(url).innerText = target ? target.time : 0;
            }
          })
          .catch(error => {
            console.error('LeanCloud Counter Error', error);
          });
      }

      const {
        app_id,
        app_key,
        server_url
      } = {
        "enable": true,
        "app_id": "povuqNsSqFodlakVIwtEX5kb-gzGzoHsz",
        "app_key": "zXD40RDtDB3DMtpC89k0AK7g",
        "server_url": null,
        "security": false
      };

      function fetchData(api_server) {
        const Counter = (method, url, data) => {
          return fetch(`${api_server}/1.1${url}`, {
            method,
            headers: {
              'X-LC-Id': app_id,
              'X-LC-Key': app_key,
              'Content-Type': 'application/json',
            },
            body: JSON.stringify(data)
          });
        };
        if (CONFIG.page.isPost) {
          if (CONFIG.hostname !== location.hostname) return;
          addCount(Counter);
        } else if (document.querySelectorAll('.post-title-link').length >= 1) {
          showTime(Counter);
        }
      }

      const api_server = app_id.slice(-9) === '-MdYXbMMI' ? `https://${app_id.slice(0, 8).toLowerCase()}.api.lncldglobal.com` : server_url;

      if (api_server) {
        fetchData(api_server);
      } else {
        fetch('https://app-router.leancloud.cn/2/route?appId=' + app_id)
          .then(response => response.json())
          .then(({
            api_server
          }) => {
            fetchData('https://' + api_server);
          });
      }
    })();
  </script>



<script>
            window.imageLazyLoadSetting = {
                isSPA: false,
                preloadRatio: 1,
                processImages: null,
            };
        </script><script>window.addEventListener("load",function(){var t=/\.(gif|jpg|jpeg|tiff|png)$/i,r=/^data:image\/[a-z]+;base64,/;Array.prototype.slice.call(document.querySelectorAll("img[data-original]")).forEach(function(a){var e=a.parentNode;"A"===e.tagName&&(e.href.match(t)||e.href.match(r))&&(e.href=a.dataset.original)})});</script><script>!function(n){n.imageLazyLoadSetting.processImages=o;var e=n.imageLazyLoadSetting.isSPA,i=n.imageLazyLoadSetting.preloadRatio||1,r=Array.prototype.slice.call(document.querySelectorAll("img[data-original]"));function o(){e&&(r=Array.prototype.slice.call(document.querySelectorAll("img[data-original]")));for(var t,a=0;a<r.length;a++)0<=(t=(t=r[a]).getBoundingClientRect()).bottom&&0<=t.left&&t.top<=(n.innerHeight*i||document.documentElement.clientHeight*i)&&function(){var t,e,n,i,o=r[a];t=o,e=function(){r=r.filter(function(t){return o!==t})},n=new Image,i=t.getAttribute("data-original"),n.onload=function(){t.src=i,e&&e()},t.src!==i&&(n.src=i)}()}o(),n.addEventListener("scroll",function(){var t,e;t=o,e=n,clearTimeout(t.tId),t.tId=setTimeout(function(){t.call(e)},500)})}(this);</script></body>

</html>